package com.ubxtech.core.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author  Victor.Xiao
 * @since 2021-03-02 16:31
 **/
public class UuidUtil {

    public static String get32UUID() {
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        return uuid;
    }

    /**
     * 根据时间戳返回Integer类型的id,从第三位截取,保留毫秒值,超过20亿则取余
     * @author Victor.Xiao
     * @since 2023-12-13 15:17
     * @return int
    */
    public static int getCurMillisIntId() {
        String curMillStr = String.valueOf(System.currentTimeMillis());
        int pre = Integer.parseInt(curMillStr.substring(3, 5));
        //大于20就可能超过Integer.MAX_VALUE
        if (pre > 20) {
            pre = pre%20;
        }
        return Integer.parseInt(pre+StrUtil.subSuf(curMillStr, 5));
    }

    /**
     * 解析出由雪花算法生成的id中的 sequence,workerId,dataCenterId,timestamp
     * @author Victor.Xiao
     * @since 2023-12-13 15:15
     * @param id id
     * @param startTime startTime
     * @return java.util.Map<java.lang.String,java.lang.Long>
    */
    public static Map<String,Long> inverseSnowFlakeId(long id,long startTime) {
        Map<String, Long> result = new HashMap<>(8);
        result.put("sequence",(id >> 22) & ~(-1L << 12));
        result.put("workerId",(id >> 12) & ~(-1L << 5));
        result.put("dataCenterId",(id >> 17) & ~(-1L << 5));
        result.put("timestamp",(id  >> 22) + startTime);
        return result;
    }


    /**
     * 解析出由雪花算法生成的id中的 sequence,workerId,dataCenterId,timestamp
     * @author Victor.Xiao
     * @since 2023-12-13 15:15
     * @param id id
     * @param startTime startTime
     * @return java.util.Map<java.lang.String,java.lang.Long>
     */
    public static Map<String,Long> inverseSnowFlakeId(long id) {
        return inverseSnowFlakeId(id, Snowflake.DEFAULT_TWEPOCH);
    }

    /**
     * 解析出由雪花算法生成的id中的 sequence,workerId,dataCenterId,timestamp
     * @author Victor.Xiao
     * @since 2023-12-13 15:15
     * @param id id
     * @param startTime startTime
     * @return java.util.Map<java.lang.String,java.lang.Long>
     */
    public static Map<String,Long> inverseSnowFlakeId(String id) {
        return inverseSnowFlakeId(Long.parseLong(id), Snowflake.DEFAULT_TWEPOCH);
    }
}
